package org.jslaughter.component.ai;

import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.World;
import org.jslaughter.event.eventtype.AggressionEvent;
import org.jslaughter.event.eventtype.AggressionListener;
import org.jslaughter.event.eventtype.PullEvent;
import org.nvframe.component.AbstractComponent;
import org.nvframe.component.ai.Behaviour.BEHAVIOUR_TYPE;
import org.nvframe.component.state.Position;
import org.nvframe.entity.Entity;
import org.nvframe.event.EventService;
import org.nvframe.manager.RegisterManager;
import org.nvframe.util.settings.SettingsObj;

public class PullBehaviour extends AbstractComponent implements AggressionListener  {
	
	private int pullRadius;
	
	private World world;

	public PullBehaviour(String id, Entity owner, SettingsObj settings) {
		super(id, owner);
		
		pullRadius = settings.getInt("pullRadius", 100);
	}
	
	public void init() {
		EventService.getInstance().addEventListener(this);
		
		world = (World) RegisterManager.getInstance().getOption("world");
	}
	
	@Override
	public void onAggressive(AggressionEvent event) {
		BehaviourImpl behaviour = (BehaviourImpl) owner.getComponent(BehaviourImpl.class);
		Position positionComp = (Position) owner.getComponent(Position.class);
		Entity target = event.getTarget();
		
		// search for teammates and pull them when needed
		for (Body body = world.getBodyList(); body.getNext() != null; body = body.getNext()) {
			if (body.isBullet())
				continue;
			
			// check if the entity is a teammate
			Entity entity = (Entity) body.getUserData();

			if(behaviour.getBehaviourTowards(entity) != BEHAVIOUR_TYPE.FRIENDLY)
				continue;
			
			// distance too far => teammate doesnt want to come
			Position entityPositionComp = (Position) entity.getComponent(Position.class);
			float distance = positionComp.getXY().distance(entityPositionComp.getXY());
			
			if(Math.abs(distance) > pullRadius)
				continue;
			
			EventService.getInstance().fireEvent(new PullEvent(owner, target), entity);
		}

	}
}
